package com.honda.util.readbyte;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class BlobDemo {
	public static void conn() {
		String URL = "jdbc:mysql://192.168.88.111:3306/esbdb_nast?serverTimezone=UTC&characterEncoding=utf8";
		String USER = "root";
		String PASSWORD = "root";
		// 1.加载驱动程序
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			// 2.获得数据库链接
			Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
			// 3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
			String requestId="VXHj3HNFgzxgdLZ3w3s";
			// int id = 1;
			//预编译
			String sql="SELECT MSG_REQUEST_BLOB,MSG_RESPONSE_BLOB,REQ_HEADER,RES_HEADER from esb_msg_datagram where  1 = 1  AND  MESSAGE_ID=? LIMIT 0,1";
			PreparedStatement statement = conn.prepareStatement(sql);
			statement.setString(1, requestId);
			ResultSet rs = statement.executeQuery();
			// 4.处理数据库的返回结果(使用ResultSet类)
			while (rs.next()) {
				System.out.println("请求报文："+getBlobInfo(rs.getObject("MSG_REQUEST_BLOB"))+"\r");
				System.out.println("响应报文："+getBlobInfo(rs.getObject("MSG_RESPONSE_BLOB"))+"\r");
				System.out.println("请求报文头："+getBlobInfo(rs.getObject("REQ_HEADER"))+"\r");
				System.out.println("响应报文头："+getBlobInfo(rs.getObject("RES_HEADER"))+"\r");
			}
			// 关闭资源
			conn.close();
			rs.close();
			statement.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static String getBlobInfo(Object obj) {
		String blobStr = "";
		try {
			if (obj instanceof byte[]) {
				byte[] byte1 = (byte[]) obj;
				System.out.println("=============");
				System.out.println(new String(byte1,"utf-8"));
				System.out.println("=============");
				String msgContext = new String(byte1,"UTF-8");
				if(msgContext.trim().substring(0, 1).equals("{")){
					blobStr=JsonFormat.formatJson(msgContext.trim());
				}else{
					blobStr=XmlForm.formatXml(msgContext.trim());
				}
				blobStr = blobStr.replace("&amp;","&").replace("&lt;","<").replace("&gt;",">").replace( "&quot;","\"").replace( "&apos;","'");

				return blobStr;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return blobStr;
	}
	public static void main(String[] args) {
		conn();


	}
}
